<template>
	<view class="search-container" :class="themeName">
		<u-sticky offset-top="0" h5-nav-height="0">
			<!-- 搜索 -->
			<view class="search-input">
				<u-search class="flex-1" v-model="search.mpkeyword" height="72" bg-color="#F4F4F4" :show-action="false"
					:placeholder="$zhTran('请输入要搜索的商品')" @focus="focusSearch" @search="handleSearch" />
				<view class="search-action" v-if="!searchStatus">
					<view v-show="goodsCardStyle === 'rectangle'" @tap="goodsCardStyle = 'square'">
						<u-icon name="grid" size="38" />
					</view>
					<view v-show="goodsCardStyle === 'square'" @tap="goodsCardStyle = 'rectangle'">
						<u-icon name="list-dot" size="38" />
					</view>
				</view>
				<view v-else class="search-action" @tap="handleSearch(search.mpkeyword)">{{ $zhTran(' 搜索 ') }}</view>
			</view>
		</u-sticky>

		<!-- 搜索 -->
		<view v-show="searchStatus" class="search-options-container">
			<view class="search-options">
				<view class="search-options-header">
					<text>{{ $zhTran('热门关键词') }}</text>
				</view>

				<view class="flex row-center">
					<u-loading mode="circle" :show="goodsSearchHistoryLoading" />
				</view>
				<template v-if="!goodsSearchHotKeyLoading">
					<view v-if="goodsSearchHotKey.length" class="search-options-main">
						<view class="search-options-item" v-for="(item, index) in goodsSearchHotKey" :key="index"
							@tap="handleSearch(item)">{{ item }}</view>
					</view>
					<view v-else class="flex row-center muted">{{ $zhTran('暂无记录') }}</view>
				</template>
			</view>
		</view>

		<!-- 搜索 -->
		<view v-show="searchStatus" class="search-options-container">
			<view class="search-options">
				<view class="search-options-header">
					<text>{{ $zhTran('历史搜索') }}</text>
					<u-icon name="trash" @tap="onSearchHistoryClear" />
				</view>

				<view class="flex row-center">
					<u-loading mode="circle" :show="goodsSearchHistoryLoading" />
				</view>
				<template v-if="!goodsSearchHistoryLoading">
					<view v-if="goodsSearchHistory.length" class="search-options-main">
						<view class="search-options-item" v-for="(item, index) in goodsSearchHistory" :key="index"
							@tap="handleSearch(item)">{{ item }}</view>
					</view>
					<view v-else class="flex row-center muted">{{ $zhTran('暂无记录') }}</view>
				</template>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view v-show="!searchStatus">
			<!-- 排序方式 -->
			<view class="sort">
				<!-- 综合 -->
				<view :class="['sort-item', { 'sort-item--active': !search.price && !search.sale }]"
					@tap="handSortOptions('all')">
					<text>{{ $zhTran('综合') }}</text>
				</view>
				<!-- 价格 -->
				<view :class="['sort-item', { 'sort-item--active': search.price }]" @tap="handSortOptions('price')">
					<text>{{ $zhTran('价格') }}</text>
					<sort-icon class="m-l-10" :status="search.price" :active-color="themeColor" />
				</view>
				<!-- 销量 -->
				<view :class="['sort-item', { 'sort-item--active': search.sale }]" @tap="handSortOptions('sale')">
					<text>{{ $zhTran('销量') }}</text>
					<sort-icon class="m-l-10" :status="search.sale" :active-color="themeColor" />
				</view>
				<!-- 商品卡片样式 -->
				<view :class="['sort-item']" @tap="showScreen = true">
					<text>{{ $zhTran('筛选') }}</text>
				</view>
			</view>

			<!-- 商品列表 -->
			<mescroll-body ref="mescrollRef" :up="{
				auto: true,
				noMoreSize: 10,
				empty: {
					icon: $getImageUri('resource/image/shopapi/uniapp/empty/shop.png'),
					tip: $zhTran('没有找到商品~'),
					fixed: true,
				},
				toTop: {
					bottom: 300
				},
			}" @init="mescrollInit" @down="downCallback" @up="upCallback" :bottom="100">
				<view :class="['goods-container', `goods-container-${goodsCardStyle}`]">
					<view class="goods-item" @click.native="goGoodsDetail(item.id)" v-for="item in goodsList"
						:key="item.id">
						<goods-card :shape="goodsCardStyle" :name="item.name" :image="item.image"
							:price="item.sell_price" :goods_model="item.goods_model" :goods_code="item.code"
							:goods_stock="item.total_stock" :minPrice="item.lineation_price"
							:member_price="item.member_price" :fieldShowHide="fieldShowHide" :fieldStyles="fieldStyles"
							:prefix="price_symbol" :spec_id="item.spec_id" :spec_type="item.spec_type"
							:spec_value="item.spec_value" :spec_value_list="item.spec_value_list"
							:understock_order_enabled="understock_order_enabled" :tag_desc="item.tag_desc"
							:aux_arr="item.aux_arr" :other_field_data="item.other_field_data"
							:field_list="fieldCommon.field[goodsCardStyle]||[]" />
					</view>
				</view>
			</mescroll-body>
		</view>
		<tabbar :common="fieldCommon" />
		<u-popup class="screen-popup" v-model="showScreen" mode="right" width="650">
			<view style="height: 100%" class="flex-col">
				<view class="screen-content">
					<scroll-view style="max-height: 100%" scroll-y="true">
						<view class="screen-item">
							<view class="bold">{{ $zhTran('品 牌') }}</view>
							<view class="brand-list flex flex-wrap m-t-30">
								<view class="brand-item m-b-20 line-1" :class="{
									active: item.id == search.brand_id,
								}" v-for="(item, index) in brandLists" :key="index" @tap="handleScreen(item)">
									{{ item.name }}
								</view>
							</view>
						</view>
					</scroll-view>
					<scroll-view style="max-height: 100%" scroll-y="true">
						<view class="screen-item">
							<view class="bold p-b-10">{{ $zhTran('分 类') }}</view>
							<u-search class="flex-1" v-model="category_keyword" height="72" bg-color="#F4F4F4"
								:show-action="false" :placeholder="$zhTran('搜索分类')" @search="searchCategory"
								@clear="searchCategory" />
							<view class="brand-list flex flex-wrap m-t-30">
								<view class="brand-item m-b-20 line-1" :class="{
									active: item.id == search.category_id,
								}" v-for="(item, index) in categoryLists" :key="index" @tap="handleCategoryScreen(item)">
									{{ item.name }}
								</view>
							</view>
						</view>
					</scroll-view>
				</view>

				<view class="screen-footer flex-1 flex">
					<button hover-class="none" class="btn btn--reset" size="md" @tap="handleReset">
						{{ $zhTran('重置') }}
					</button>
					<button hover-class="none" class="btn btn--confirm" size="md" @tap="handleConfirm">
						{{ $zhTran('确定') }}
					</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		apiGetPage
	} from "@/api/store";
	import {
		apiGoodsLists,
		apiBrandLists,
		apiSearchCategory,
	} from "@/api/goods";
	import {
		apiSearchHistory,
		apiSearchHistoryClear,
		apiSearchHotKey
	} from "@/api/goods";
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";

	export default {
		name: "Search",
		mixins: [MescrollMixin],

		data() {
			return {
				showScreen: false,
				goodsList: [], // 商品列表
				goodsSearchHistory: [], // 商品搜索记录
				goodsSearchHistoryLoading: true, // 搜索记录请求状态loading
				goodsSearchHotKey: [], // 热门关键词
				goodsSearchHotKeyLoading: true, // 搜索记录请求状态loading
				searchStatus: false, // 搜索状态
				goodsCardStyle: "square", // 商品卡片样式: square -正方形; rectangle -长方形
				search: {
					mpkeyword: "", // 商品名称
					category_id: "", // 分类
					price: "", // 价格排序: desc-降序; asc-升序;
					sale: "", // 销量排序: desc-降序; asc-升序;
					brand_id: "", //品牌
				},
				category_keyword: '',
				// 品牌列表
				brandLists: [],
				// 商品列表
				categoryLists: [],
				fieldShowHide: {},
				fieldStyles: {},
				fieldCommon: {},
				price_symbol: '￥',
				understock_order_enabled: 0
			};
		},

		methods: {
			// 初始化Mescroll
			mescrollInit(mescroll) {
				console.log(mescroll);
				this.mescroll = mescroll;
			},

			// 下拉刷新
			downCallback() {
				this.mescroll.resetUpScroll();
			},

			// 上拉加载更多
			upCallback(page) {
				if (this.searchStatus) return;

				const pageNum = page.num;
				const pageSize = page.size;

				apiGoodsLists({
						...this.search,
						page_no: pageNum,
						page_size: pageSize,
					})
					.then(({
						lists,
						page_size,
						count,
						extend
					}) => {
						// 如果是第一页需手动置空列表
						if (page.num == 1) this.goodsList = [];
						// 重置列表数据
						this.goodsList = [...this.goodsList, ...lists];
						this.goodsList = this.$zhTran(this.goodsList)
						// this.mescroll.endBySize(page_size, count)
						this.mescroll.endSuccess(lists.length, count);
						this.price_symbol = extend.price_symbol
						this.understock_order_enabled = extend.understock_order_enabled
					})
					.catch(() => {
						this.mescroll.endErr();
					});
			},

			// 获取分类信息
			getCategoryInfo() {
				apiGetPage({
					type: 2,
				}).then((nres) => {
					let res = this.$zhTran(nres)
					this.fieldCommon = res.common
					if (res.common.search_style) {
						this.goodsCardStyle = res.common.search_style
					}
					this.fieldShowHide = res.content[1].content
					this.fieldStyles = res.content[1].styles
					console.log('fieldShowHide', this.fieldShowHide)

					for (var i in res.common) {
						if (this.fieldShowHide[i] != undefined) this.fieldShowHide[i] = res.common[i]
					}
					this.fieldShowHide.style = 2

					delete this.fieldShowHide.data
				});
			},


			// 跳转商品详情
			goGoodsDetail(id) {
				this.$Router.push({
					path: "/bundle2/pages/goods_detail/goods_detail",
					query: {
						id,
					},
				});
			},
			// 聚焦搜索
			focusSearch() {
				this.searchStatus = true;
				this.initSearchHistoryData();
			},

			// 搜索
			handleSearch(value) {
				this.searchStatus = false;
				this.$set(this.search, "mpkeyword", value);
				this.mescroll && this.mescroll.resetUpScroll();
			},

			// 清空搜索记录
			onSearchHistoryClear() {
				uni.showModal({
					title: this.$zhTran("温馨提示"),
					content: this.$zhTran("是否清空搜索记录?"),
					confirmColor: this.themeColor,
					success: ({
						confirm
					}) => {
						if (!confirm) return;
						apiSearchHistoryClear()
							.then(() => {
								this.initSearchHistoryData();
							})
							.catch(() => {
								this.$toast({
									title: this.$zhTran("操作失败"),
								});
							});
					},
				});
			},

			// 排序方式
			handSortOptions(type) {
				switch (type) {
					case "all":
						this.$set(this.search, "sale", "");
						this.$set(this.search, "price", "");
						break;
					case "sale":
						this.$set(this.search, "price", "");
						this.$set(this.search, "sale", this.getSortReverse(this.search.sale));
						break;
					case "price":
						this.$set(this.search, "sale", "");
						this.$set(this.search, "price", this.getSortReverse(this.search.price));
						break;
				}
				// 重载数据
				this.mescroll.resetUpScroll();
			},

			// 获取反向排序
			getSortReverse(sort) {
				switch (sort) {
					case "asc":
						return "desc";
					case "desc":
						return "asc";
					default:
						return "desc";
				}
			},

			// 初始化搜索记录数据
			initSearchHistoryData() {
				apiSearchHistory()
					.then((data) => {
						this.goodsSearchHistory = data;
					})
					.catch((err) => {
						this.$toast({
							title: this.$zhTran("搜索记录获取失败"),
						});
						throw new Error(err);
					})
					.finally(() => {
						this.goodsSearchHistoryLoading = false;
					});
				apiSearchHotKey()
					.then((data) => {
						this.goodsSearchHotKey = data;
					})
					.catch((err) => {
						this.$toast({
							title: this.$zhTran("热门关键词获取失败"),
						});
						throw new Error(err);
					})
					.finally(() => {
						this.goodsSearchHotKeyLoading = false;
					});
			},
			//筛选条件
			getSearchList() {
				this.searchCategory()
				this.searchBrandLists()
			},
			searchCategory() {
				apiSearchCategory({
					keyword: this.category_keyword,
				}).then((res) => {
					this.categoryLists = res
				});
			},
			searchBrandLists() {
				apiBrandLists({
					page_type: 1,
				}).then((res) => {
					this.brandLists = res.lists;
				});
			},
			// 选中条件
			handleScreen(item) {
				this.search.brand_id = item.id;
			},
			handleCategoryScreen(item) {
				this.search.category_id = item.id;
			},
			// 确定
			handleConfirm() {
				this.showScreen = false;
				this.mescroll.resetUpScroll();
			},
			// 重置
			handleReset() {
				this.search.brand_id = "";
				this.search.category_id = "";
				this.category_keyword = ''
				this.searchCategory()
				this.showScreen = false;
				this.mescroll.resetUpScroll();
			},
		},

		onLoad() {
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}
			const options = this.$Route.query;
			if (JSON.stringify(options) !== "{}") {
				if (!!options.id) {
					if (options.type == 'brand') {
						this.$set(this.search, "brand_id", options.id)
					} else {
						this.$set(this.search, "category_id", options.id)
					}
					console.log('search', this.search)
					this.handleSearch("");
				}
				// !!options.name && this.handleSearch(options.name)
			}
			this.getCategoryInfo()
			// 获取历史搜素内容
			this.initSearchHistoryData();
			this.getSearchList();
		},
	};
</script>

<style lang="scss" scoped>
	.search-container {
		display: flex;
		flex-direction: column;
	}

	.search-input {
		display: flex;
		align-items: center;
		height: 100rpx;
		padding: 0 20rpx;
		background-color: #ffffff;

		.search-action {
			width: 100rpx;
			text-align: center;
		}
	}

	.search-options-container {
		box-sizing: border-box;
		height: 100vh;
		padding: 0 20rpx;
		background-color: #ffffff;

		.search-options {
			&-header {
				display: flex;
				justify-content: space-between;
				padding: 30rpx 0 24rpx 0;
				font-size: $-font-size-nr;
			}

			&-main {
				display: flex;
				flex-wrap: wrap;
			}

			&-item {
				padding: 8rpx 24rpx;
				margin: 0 16rpx 24rpx 0;
				border-radius: 60px;
				background-color: #f4f4f4;
			}
		}
	}

	.sort {
		display: flex;
		align-items: center;
		height: 80rpx;
		font-size: $-font-size-nr;
		background-color: #ffffff;

		&-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		&-item--active {
			@include font_color();
		}

		&-style {
			position: relative;
			width: 100rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			&::before {
				position: absolute;
				top: 50%;
				left: 0;
				transform: translateY(-50%);
				display: block;
				content: "";
				height: 1em;
				border-left: $-solid-border;
			}
		}
	}

	.goods-container {
		flex: 1;
		display: flex;
		padding: 0 20rpx;

		&-square {
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: space-between;
		}

		&-rectangle {
			flex-direction: column;
		}

		.goods-item {
			margin-top: 16rpx;
		}
	}

	.screen-popup {
		.screen-content {
			height: calc(100% - 100rpx - env(safe-area-inset-bottom));

			.screen-item {
				padding: 20rpx;
			}

			.brand-list {
				border-radius: 10rpx;

				.brand-item {
					width: 190rpx;
					padding: 0 20rpx;
					border: 1px solid transparent;
					background-color: #f5f5f5;
					line-height: 60rpx;
					border-radius: 60rpx;
					text-align: center;

					&.active {
						@include border_color();
						@include background_color(0.3);
						@include font_color();
					}

					&:not(:nth-of-type(3n)) {
						margin-right: 20rpx;
					}
				}
			}
		}

		.screen-footer {
			padding: 0 20rpx env(safe-area-inset-bottom);

			.btn {
				flex: 1;
				border-radius: 60rpx;

				&--reset {
					@include font_color() border: 1px solid currentColor;
					margin-right: 20rpx;
				}

				&--confirm {
					@include background_color();
					color: #fff;
				}
			}
		}
	}
</style>